using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Project.EPMSync.Config.Library;
using System.Collections;
using PSLibrary = Microsoft.Office.Project.Server.Library;
using System.Web.Services.Protocols;
using System.Net;
using System.Globalization;

namespace Microsoft.Office.Project.EPMSync.Service
{
    /// <summary>
    /// Implements list of project names associate with it's Guid in an enumerable collection
    /// </summary>
    class ProjectCollection : IEnumerable
    {
        private Tracing _tracing;
        private ProjectWS.Project _projWebSvc;
        Dictionary<string, Guid> _projectList;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="tracing">Pointer to the active tracing component.</param>
        /// <param name="projWebSvc">Connection to the Project web service</param>
        public ProjectCollection(Tracing tracing, ProjectWS.Project projWebSvc)
        {
            _tracing = tracing;
            _projWebSvc = projWebSvc;
        }

        /// <summary>
        /// Implemented to allow enumeration of the collection
        /// </summary>
        /// <returns>IEnumerator which allows enumeration of the collection.</returns>
        public IEnumerator GetEnumerator()
        {
            return _projectList.GetEnumerator();
        }

        /// <summary>
        /// Check if a project specifed by name is in the list
        /// </summary>
        /// <param name="projectName">The name of the project being searched for.</param>
        /// <returns>True if the project is part of the list.</returns>
        public bool Contains(string projectName)
        {
            if (_projectList != null)
                return _projectList.ContainsKey(FormatProjectName(projectName));
            else
                return false;
        }

        /// <summary>
        /// Makes sure the list of projects has been read
        /// </summary>
        /// <returns>True if the project list has been intialized.</returns>
        public bool FillProjectList()
        {
            if (_projectList != null)
                _projectList.Clear();
            else
                _projectList = new Dictionary<string, Guid>();

            ProjectWS.ProjectDataSet pds;
            try
            {
                pds = _projWebSvc.ReadProjectStatus(Guid.Empty, ProjectWS.DataStoreEnum.PublishedStore, string.Empty, (int)PSLibrary.Project.ProjectType.Project);
                foreach (ProjectWS.ProjectDataSet.ProjectRow pr in pds.Project)
                {
                    //_countProjects++;
                    _projectList.Add(FormatProjectName(pr.PROJ_NAME), pr.PROJ_UID);
                }
                pds = _projWebSvc.ReadProjectStatus(Guid.Empty, ProjectWS.DataStoreEnum.PublishedStore, string.Empty, (int)PSLibrary.Project.ProjectType.MasterProject);
                foreach (ProjectWS.ProjectDataSet.ProjectRow pr in pds.Project)
                {
                    //_countProjects++;
                    _projectList.Add(FormatProjectName(pr.PROJ_NAME), pr.PROJ_UID);
                }
                pds = _projWebSvc.ReadProjectStatus(Guid.Empty, ProjectWS.DataStoreEnum.PublishedStore, string.Empty, (int)PSLibrary.Project.ProjectType.LightWeightProject);
                foreach (ProjectWS.ProjectDataSet.ProjectRow pr in pds.Project)
                {
                    //_countProjects++;
                    _projectList.Add(FormatProjectName(pr.PROJ_NAME), pr.PROJ_UID);
                }
                pds = _projWebSvc.ReadProjectStatus(Guid.Empty, ProjectWS.DataStoreEnum.PublishedStore, string.Empty, (int)PSLibrary.Project.ProjectType.InsertedProject);
                foreach (ProjectWS.ProjectDataSet.ProjectRow pr in pds.Project)
                {
                    //_countProjects++;
                    _projectList.Add(FormatProjectName(pr.PROJ_NAME), pr.PROJ_UID);
                }
            }
            catch (SoapException ex)
            {
                _tracing.WriteTrace(_tracing.MainSwitch.TraceError, String.Format(CultureInfo.InvariantCulture, "A SOAP exception occurred during ReadProjectStatus: \r\n{0}", PSError.FormattedMessage(ex)));
                return false;
            }
            catch (WebException ex)
            {
                _tracing.WriteTrace(_tracing.MainSwitch.TraceError, String.Format(CultureInfo.InvariantCulture, "An WebException occurred during ReadProjectStatus: \r\n{0}", ex.Message));
                return false;
            }
            catch (Exception ex)
            {
                _tracing.WriteTrace(_tracing.MainSwitch.TraceError, String.Format(CultureInfo.InvariantCulture, "An exception occurred during ReadProjectStatus: \r\n{0}", ex.Message));
                return false;
            }

            return true;

        }

        /// <summary>
        /// Searched the list for the specified project name.
        /// </summary>
        /// <param name="projectName">The name of the project being searched for.</param>
        /// <returns>Guid of the project if the project is part of the list.  Returns Guid Empty
        /// if the project name is not found.</returns>
        public Guid getProjectID(string projectName)
        {
            bool tryAgain = true;
            int tryCount = 1;
            do
            {
                try
                {
                    return _projectList[FormatProjectName(projectName)];
                }
                catch (KeyNotFoundException)
                {
                    if (tryCount++ == 2)
                        tryAgain = false;
                    else
                    {
                        // Reread the project list from Project Server to check for changes.
                        FillProjectList();
                    }
                }
            }
            while (tryAgain);

            // A valid project was not found in the list
            return Guid.Empty;

        }

        /// <summary>
        /// Cleans up the project name string.
        /// </summary>
        /// <param name="projectName">The input project name.</param>
        /// <returns>The formatted project name.</returns>
        public static string FormatProjectName(string projectName)
        {
            string proj = projectName.Trim();
            return proj.ToLower(CultureInfo.InvariantCulture);
        }


    }
}
